﻿using System;
using System.ComponentModel.Composition;
using System.Diagnostics;
using Zero.Common;

namespace Zero.Frontend
{
    [Export(typeof(IBackend)), Export(typeof(ITypedBackend))]
    class ServiceBackend : IBackend, ITypedBackend
    {
        public ServiceBackend()
        {
            _client = new Service.Client();
        }

        private readonly Service.Client _client;

        public object Process(object request)
        {
            Stopwatch w = Stopwatch.StartNew();

            var returned = _client.ProcessObject(new TransportObject(request));
            if (returned == null)
            {
                throw new ApplicationException("Service returned null.");
            }

            Debug.WriteLine("Backend call took: "+ w.ElapsedMilliseconds + "ms");

            return returned.Data;
        }

        public TResponse Process<TResponse>(IRequest<TResponse> request)
        {
            return (TResponse) Process((object)request);
        }
    }
}
